window.log = function () {
    console.log.apply(console, arguments);
};

/**
 * 操作url的查询字段
 *
 * @param url
 */
function objURL(url) {
    var ourl = url || window.location.href;
    var href = "";//?前面部分
    var params = {};//url参数对象
    var jing = "";//#及后面部分

    var init = function () {
        var str = ourl;
        var index = str.indexOf("#");
        if (index > 0) {
            jing = str.substr(index);
            str = str.substring(0, index);
        }

        index = str.indexOf("?");
        if (index > 0) {
            href = str.substring(0, index);
            str = str.substr(index + 1);
            var parts = str.split("&");
            for (var i = 0; i < parts.length; i++) {
                var kv = parts[i].split("=");
                params[kv[0]] = kv[1];
            }
        } else {
            href = ourl;
            params = {};
        }
    };

    this.set = function (key, val) {
        params[key] = encodeURIComponent(val);

        return this;
    };

    this.remove = function (key) {
        if (key in params) params[key] = undefined;

        return this;
    };

    this.get = function (key) {
        return params[key];
    };

    this.url = function (key) {
        var strurl = href;
        var objps = [];
        for (var k in params) {
            if (params[k]) {
                objps.push(k + "=" + params[k]);
            }
        }

        if (objps.length > 0) {
            strurl += "?" + objps.join("&");
        }

        if (jing.length > 0) {
            strurl += jing;
        }
        return strurl;
    };

    this.debug = function () {
        // 以下调试代码自由设置
        var objps = [];
        for (var k in params) {
            objps.push(k + "=" + params[k]);
        }
        alert(objps);//输出params的所有值
    };
    init();
}

/**
 * 判断是不是整数
 *
 * @param value
 * @returns {boolean}
 */
function isInt(value) {
    return Math.floor(value) === Number(value);
}

/**
 * 返回一个限制表单提交多次的对象
 */
function submitControl() {
    var o = {
        /**
         * 请求时,显示loading遮罩层
         */
        loading: true,

        /**
         * 请求是否正在进行中
         */
        submitting: false,

        /**
         * 表单中的提交按钮,用来在提交后,设置为disabled
         */
        form: null,

        /**
         * 表单中的所有:input元素
         */
        allInputs: null,

        /**
         * loading弹框的index
         */
        loadLayerIndex: -1,

        /**
         * 控制哪些状态需要恢复的设置
         */
        resetSettings: {
            /**
             * 提交中的状态
             */
            status: true,

            /**
             * 表单元素的禁用状态
             */
            form: true,

            /**
             * 弹框
             */
            layer: true,
        },
    };

    var disableInputs = function (disabled) {
        if (disabled === undefined) {
            disabled = true;
        }

        disabled = Boolean(disabled);

        o.allInputs && o.allInputs.prop('disabled', disabled);

        layui.form.render();
    };

    /**
     * 开始发送请求,如果正在请求中,则返回false,以便中断请求
     *
     * @returns {boolean}
     */
    o.go = function () {
        if (o.submitting) {
            return false;
        }

        o.submitting = true;
        disableInputs();
        o.loading && (o.loadLayerIndex = layer.load(2, {shade: 0.2}));

        return true;
    };

    /**
     * 请求完成后,用来重置按钮,关闭加载弹框
     */
    o.done = function () {
        var resetSettings = o.resetSettings;

        resetSettings.status && (o.submitting = false);
        resetSettings.form && disableInputs(false);
        resetSettings.layer && layer.close(o.loadLayerIndex);
    };

    /**
     * 设置本次提交的表单
     *
     * @param form
     */
    o.setForm = function (form) {
        o.form = form;
        o.allInputs = o.form.find(':input');
    };

    /**
     * 设置本次提交的所有输入元素
     *
     * @param inputs
     */
    o.setInputs = function (inputs) {
        o.allInputs = inputs;
    };

    /**
     * 某些情况下,需要设置请求完成后,哪些状态需要恢复
     *
     * @param settings
     */
    o.setReset = function (settings) {
        if (settings === undefined) {
            settings = {};
        }

        $.each(o.resetSettings, function (key) {
            if (settings[key] !== undefined) {
                o.resetSettings[key] = Boolean(settings[key]);
            }
        });
    };

    /**
     * 禁用loading弹出层
     */
    o.noLoading = function () {
        o.loading = false;
    };

    return o;
}

/**
 * 显示表单验证消息
 *
 * @param msgBag laravel返回的错误包
 * @param toastValidate 是否用toastr显示错误消息,默认在表单下面以红字显示
 * @param form 本次提交的表单(可选)
 */
function showValidateErrors(msgBag, toastValidate, form) {
    msgBag = msgBag.errors;

    if (toastValidate) {
        $.each(msgBag, function (_, field) {
            $.each(field, function (_, error) {
                toastr.error(error);
            });
        });
    } else {
        if (!form) {
            $.each(msgBag, function (key) {
                form = $('[data-validate=' + key + ']').closest('form');
                if (form.length > 0) {
                    return false;
                }
            });
        }

        form.find('[data-validate]').each(function () {
            var thisValidateBox = $(this);
            var keys = thisValidateBox.data('validate').split('|');

            var msgHtml = '';

            $.each(keys, function (_, key) {
                if (msgBag[key] !== undefined) {
                    if (msgBag[key] instanceof Array) {
                        $.each(msgBag[key], function (_, error) {
                            msgHtml += '<p>' + error + '</p>';
                        });
                    } else {
                        msgHtml += '<p>' + msgBag[key] + '</p>';
                    }
                }
            });

            thisValidateBox.html(msgHtml);
        });
    }
}

/**
 * 清除错误提示消息
 *
 * @param input 正在输入的form元素
 */
function clearValidateErrors(input) {
    // 就用最简单的办法找到对应的错误信息,然后清除
    input.closest('.layui-form-item').find('[data-validate]').html('');
}

/**
 * MDN上的cookie操作
 */
var docCookies = {
    getItem: function (sKey) {
        return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
    },
    setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
        if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) {
            return false;
        }
        var sExpires = "";
        if (vEnd) {
            switch (vEnd.constructor) {
                case Number:
                    sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
                    break;
                case String:
                    sExpires = "; expires=" + vEnd;
                    break;
                case Date:
                    sExpires = "; expires=" + vEnd.toUTCString();
                    break;
            }
        }
        document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
        return true;
    },
    removeItem: function (sKey, sPath, sDomain) {
        if (!sKey || !this.hasItem(sKey)) {
            return false;
        }
        document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
        return true;
    },
    hasItem: function (sKey) {
        return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
    },
    keys: /* optional method: you can safely remove it! */ function () {
        var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
        for (var nIdx = 0; nIdx < aKeys.length; nIdx++) {
            aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]);
        }
        return aKeys;
    }
};